import React from 'react';
import { NavigateOptions, useNavigate as OriginUseNavigate, Path as OriginPath, To } from 'react-router-dom'

interface Path extends OriginPath {
    query?: { [key: string]: string | number }
}

type ToParam = To | Partial<Path>


export interface NavigateFunction {
    (to: ToParam, options?: NavigateOptions): void;
    (delta: number): void;
}

export const useNavigate = (): NavigateFunction => {
    const navigate = OriginUseNavigate()
    const func = React.useCallback((to: ToParam | number, options?: NavigateOptions) => {
        if (typeof to === 'number') {
            navigate(to)
        } else {
            if (typeof to === 'string') {
                navigate(to, options)
                return
            }

            if ('query' in to && to.query) {
                const paths = to.pathname?.split('/')
                const path = paths?.reduce((draft: string, str: string, idx: number) => {
                    let temp = str
                    if (str.startsWith(':')) {
                        const key = temp.substring(1)
                        temp = String(to.query![key] || temp)
                    }
                    if (idx === paths.length - 1) {
                        draft += `${temp}`
                    } else {
                        draft += `${temp}/`
                    }
                    return draft
                }, '')
                to.pathname = path
            }

            navigate(to, options)
        }
    }, [navigate]);
    return func

}